package com.umfwechat.h5.controller.settlement;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.umfwechat.common.ReqMessage;
import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.constant.ConfigConsts;
import com.umfwechat.common.constant.MsgConsts;
import com.umfwechat.common.constant.ValueConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.util.HttpUtil;
import com.umfwechat.util.RandomUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.ResultJsonUtil;
import com.umfwechat.util.StringUtil;
import com.umpay.operation.model.edrawInf.EdrawInf;
import com.umpay.operation.service.edrawInf.remote.EdrawInfServiceRemote;
import com.umpay.sp.util.AmountUtil;

/**
 * 提前结算申请
 * @author css
 *
 */
@Controller
@RequestMapping("h5/earlyPayController")
public class EarlyPayController {

	@Resource
	EdrawInfServiceRemote edrawInfServiceRemote;
	
	private static Logger logger = LoggerFactory.getLogger(EarlyPayController.class);
	
	/**
	 * 提前结算申请页面初始化接口
	 * @param request
	 * @param response
	 * @param merId
	 * @return
	 */
 	@RequestMapping(value="/earlyPayInitial",method = {RequestMethod.POST,RequestMethod.GET },produces="text/html;charset=UTF-8")
	@ResponseBody
	public String earlyPayInitial(HttpServletRequest request, HttpServletResponse response ,String merId ){
		logger.info("【提前结算申请页面初始化接口】开始");
		try {
			Map<String, Object> resMp = new HashMap<String, Object>();
			if(StringUtil.isEmpty(merId)){
				logger.info("获取前提merId为空！");
				return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433077);
			}
			//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~可借额度查询接口~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
			String url = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.LIMITAMOUNT);
//			 = "http://10.10.77.90:8084/borrow/B01001";
			Map<String , Object> param = new HashMap<String, Object>();
			ReqMessage req = ReqMessageUtil.makeReq();
			param.put(CommonConsts.RPID, StringUtil.trim(req.getRpid()));
			param.put(CommonConsts.REQDATE, StringUtil.trim(req.getReqDate()));
			param.put(CommonConsts.REQTIME, StringUtil.trim(req.getReqTime()));
			param.put(CommonConsts.MERID, merId);
			logger.info("【查询商户可借额度查询接口】入参" + param);
			logger.info("请求地址" + url);
			Map<String, Object> resMap = HttpUtil.httpPostForm2Xml(url, param);
			logger.info("【查询商户可借额度查询接口】出参" + resMap);
			if(resMap.get(CommonConsts.RETCODE).equals(ValueConsts.LIMITAMOUNT_ZERO)){	//待结算可借余额为零
				logger.info("待结算可借余额为0！");
				String limitAmount = ValueConsts.ZERO;
				resMp.put("limitAmount", limitAmount);
			}
			if(resMap.get(CommonConsts.RETCODE).equals(ValueConsts.OUT_TIME)){	//不在运营时间内
				logger.info("提前结算功能不在运营时间内！");
				return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433113);
			}
			if(!resMap.get(CommonConsts.RETCODE).equals(RetCode.SUCCESS) && !resMap.get(CommonConsts.RETCODE).equals(ValueConsts.LIMITAMOUNT_ZERO) 
					&& !resMap.get(CommonConsts.RETCODE).equals(ValueConsts.OUT_TIME) ){
				if(resMap.get(CommonConsts.RETCODE).equals(ValueConsts.NO_PRODUCT)){
					logger.info("商户未开通此产品！");
					return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433114);
				}
				logger.info("查询商户可接额度接口失败！可借额度为0！");
				String limitAmount = ValueConsts.ZERO;
				resMp.put("limitAmount", limitAmount);
//				return ResultJsonUtil.resultJson(RetCode.SUCCESS, MsgConsts.E00433016 , resMp );
			}
			if(resMap.get(CommonConsts.RETCODE).equals(RetCode.SUCCESS)){
				String limitAmount = resMap.get("limitAmount").toString();
				//分转元
				limitAmount = AmountUtil.Cent2Dollar(limitAmount);
				logger.info("可借额度为limitAmount：" + limitAmount);
				resMp.put("limitAmount", limitAmount);
			}
			//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~查询商户绑卡信息接口~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
			com.umpay.operation.common.ReqMessage reqM = ReqMessageUtil.makeOpReq();
			Map<String, Object> reqMap = new HashMap<String, Object>();
			reqMap.put(CommonConsts.MERID, merId);
		    reqMap.put(CommonConsts.DELAYDAYS, ValueConsts.EDRAW_DELAYDAYS);
		    reqMap.put(CommonConsts.STATE, ValueConsts.EDRAW_STATE);
		    reqMap.put(CommonConsts.RECVBANKACCPRO, ValueConsts.EDRAW_RECVBANKACCPRO);
		    reqM.setReqMap(reqMap);
			logger.info("【查询商户绑定银行卡信息接口】入参：" + reqM);
			com.umpay.operation.common.ResMessage res = edrawInfServiceRemote.queryEdrewInf(reqM);
			logger.info("【查询商户绑定银行卡信息接口】出参：" + res);
			if(!res.getRetCode().equals(RetCode.SUCCESS)){			//查询失败
				logger.info("调用查询商户绑卡信息接口失败!");
				return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433058);
			} 
			EdrawInf edrawInfReDataInfo =(EdrawInf) res.getResMap().get(CommonConsts.EDRAWINF);
			logger.info("查询商户绑定的银行卡信息为edrawInfReData：！" + edrawInfReDataInfo);
			if( edrawInfReDataInfo == null ){		//查询无数据
				logger.info("调用查询商户绑卡信息接口无数据!merId："+merId);
				return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433080);
			}
			EdrawInf edrawInfNew = new EdrawInf();
			edrawInfNew.setMerId(edrawInfReDataInfo.getMerId());
			edrawInfNew.setBinBankId(edrawInfReDataInfo.getBinBankId());
			edrawInfNew.setBankName(edrawInfReDataInfo.getBankName());
			edrawInfNew.setBankAccount(edrawInfReDataInfo.getBankAccount());
			edrawInfNew.setColAccName(edrawInfReDataInfo.getColAccName());
			edrawInfNew.setDelayDays(edrawInfReDataInfo.getDelayDays());
			edrawInfNew.setState(edrawInfReDataInfo.getState());
			edrawInfNew.setRecvBankAccPro(edrawInfReDataInfo.getRecvBankAccPro());
			resMp.put(CommonConsts.EDRAWINFREDATA, edrawInfNew);
			//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~商户费率查询接口~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//			String urlFl = "http://10.10.77.90:8084/borrow/B01006";
//			Map<String , Object> paramFl = new HashMap<String, Object>();
//			ReqMessage reqMess = ReqMessageUtil.makeReq();
//			paramFl.put(CommonConsts.RPID, StringUtil.trim(reqMess.getRpid()));
//			paramFl.put(CommonConsts.REQDATE, StringUtil.trim(reqMess.getReqDate()));
//			paramFl.put(CommonConsts.REQTIME, StringUtil.trim(reqMess.getReqTime()));
//			paramFl.put(CommonConsts.MER_ID, merId);
//			logger.info("【查询商户费率查询接口】入参" + req);
//			Map<String, Object> resMesMap = HttpUtil.httpPostForm2Xml(urlFl, paramFl);
//			logger.info("【查询商户费率查询接口】出参" + resMesMap);
//			if(!resMesMap.get(CommonConsts.RETCODE).equals(RetCode.SUCCESS)){
//				logger.info("查询商户费率查询接口失败！");
//				return ResultJsonUtil.resultJson(RetCode.FAIL, "查询商户可借额度接口失败！");
//			}
//			String feeType = resMesMap.get("feeType").toString();//费率类型
//			String feeRate = resMesMap.get("feeRate").toString();//费率值？？？？？？？？？？？？
//			String minAmount = null ;
//			if(feeType.equals("1")){//单笔百分比
//				
//			}
			//~~~~~~~~~~~~~~~~~~~配置文件中读取费率~~~~~~~~~~~~~~~~~~~
			String feeRate =UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PAYMENT_ACC_FEE_DATE);
			String a[] = feeRate.split("&");
			feeRate = a[3];
			logger.info("取出费率为feeRate：" + feeRate);
			if(StringUtil.isEmpty(feeRate)){
				logger.info("取出费率为feeRate为空");
				return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433115);
			}
			resMp.put(CommonConsts.FEERATE , feeRate);
			//~~~~~~~~~~~~~~~~最低结算金额~~~~~~~~~~~~~~~~~~~
			String minAmount = null ;
//			BigDecimal bignum = new BigDecimal("0.5");
//			BigDecimal bigFeeRate = new BigDecimal(feeRate);
//			System.out.println(bignum.divide(bigFeeRate ,2, BigDecimal.ROUND_HALF_UP));
//			minAmount = bignum.divide(bigFeeRate , 2 ,BigDecimal.ROUND_HALF_UP).toString();
			minAmount = a[1];
			minAmount = AmountUtil.Cent2Dollar(minAmount);
			logger.info("最低提现金额为minAmount：" + minAmount);
			resMp.put(CommonConsts.MINAMOUNT , minAmount);
			//~~~~~~~~~~~~~~~~~~~当前时间~~~~~~~~~~~~~~~~~~~
			SimpleDateFormat df = new SimpleDateFormat(ValueConsts.TIME);//设置日期格式
			String currentTime = df.format(new Date());// new Date()为获取当前系统时间
			logger.info("获取当前系统时间currentTime：" + currentTime);
			resMp.put(CommonConsts.CURRENTTIME, currentTime);
			//~~~~~~~~~~~~~~~~~~~订单号~~~~~~~~~~~~~~~~~~~
			String orderId = null ;
			SimpleDateFormat date = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String dateString = date.format(new Date());
			orderId = merId + dateString;
//			orderId = RandomUtil.getRandomNumAndLetter(32);
			logger.info("生成商户订单号orderId：" + orderId);
			resMp.put(CommonConsts.ORDERID, orderId);
			return ResultJsonUtil.resultJson(RetCode.SUCCESS, MsgConsts.I00433111 , resMp);
		} catch (Exception e) {
			logger.info("提前结算申请页面初始化接口失败！"); 
		}
		return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433016);
	}
}
